import type { RequestInstance } from '@sa/axios';
import type { AxiosInstance, AxiosResponse } from 'axios';

import { router } from '@/features/router/router';

import type { RequestInstanceState } from './types';
export async function backendFail(
  response: AxiosResponse<App.Service.Response<unknown>, any>,
  instance: AxiosInstance,
  request: RequestInstance<RequestInstanceState>,
) {
  const responseCode = String(response.data.code);

  function handleLogout() {
    const location = router.reactRouter.state.location;
    const fullPath = location.pathname + location.search + location.hash;
    router.push('/login-out', { query: { redirect: fullPath } });
  }

  function logoutAndCleanup() {
    handleLogout();
    window.removeEventListener('beforeunload', handleLogout);
    request.state.errMsgStack = request.state.errMsgStack.filter((msg) => msg !== response.data.msg);
  }

  const logoutCodes = import.meta.env.PUBLIC_SERVICE_LOGOUT_CODES?.split(',') || [];
  if (logoutCodes.includes(responseCode)) {
    handleLogout();
    return null;
  }

  const modalLogoutCodes = import.meta.env.PUBLIC_SERVICE_MODAL_LOGOUT_CODES?.split(',') || [];
  if (modalLogoutCodes.includes(responseCode) && !request.state.errMsgStack?.includes(response.data.msg)) {
    request.state.errMsgStack = [...(request.state.errMsgStack || []), response.data.msg];
  }
}
